import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session, Dict } from '/@/utils/storage';
import { useLoginApi } from '/@/api/login';
const loginApi = useLoginApi();

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userId: '',
            username: '',
            name: '',
            authorities: [],
            roleList: [],
            menus: [],
            time: 0,
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
                Dict.setList(this.userInfos.dict)
			} else {
				const userInfos: any = await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		async getApiUserInfo() {
			let res = await loginApi.current();
            if(res) {
                const { user, authorities, menus, dict } = res.data
                Dict.setList(dict)
                // 用户信息模拟数据
                const userInfos = {
                    userId: user.userId,
                    username: user.username,
                    authorities: authorities,
                    name: user.name,
                    menus,
                    dict,
                    roleList: user.roleList,
                    time: new Date().getTime(),
                };
                Session.set('userInfo', userInfos);
                return userInfos;
            }
            return {}
		},
	},
});
